# -*- coding: utf-8 -*-
"""
@Time ： 2021/1/21 一缕青丝伴忧愁:14
@Auth ： 张张呀
@File ：__init__.py.py
@IDE ：PyCharm
@Motto：ABC(Always Be Coding)

"""

import os
from tkinter import *
from tkinter import messagebox

import easygui
import requests
from lxml import etree
from pypinyin import lazy_pinyin


def main():
    top = Tk()
    top.withdraw()
    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.183 Safari/537.36'
    }
    typelist = ['fengjing', 'meinv', 'youxi', 'dongman', 'yingshi', 'mingxing', 'qiche', 'dongwu', 'renwu',
                'meishi', 'zongjiao', 'beijing']

    print('4K风景,4K美女,4K游戏,4K动漫,4K影视,4K明星,4K汽车,4K动物,4K人物,4K美食,4K宗教,4K背景')

    fenlei = easygui.multchoicebox(msg="请选择你要爬取的分类(支持多选)", title="分类",
                                   choices=("风景", "美女", "游戏", "动漫", "影视", "明星", "汽车", "动物", "人物", "美食", "背景", "宗教"))
    (start, end) = easygui.multenterbox('千图网分类爬取', 'Python爬取高清图片',
                                        fields=['请输入要爬取的起始页(开始页,默认1)',
                                                '请输入要爬取的起始页(结束页,默认50)'],
                                        values=['1', '50'])
    for inx, type in enumerate(fenlei):
        res = True  # 判断是否全为中文 是中文就返回True
        for w in type:
            if not '\u4e00' <= w <= '\u9fff':
                res = False
        if not res:  # 如果不是中文直接赋值给new_searchtype
            new_searchtype = type
            if new_searchtype not in typelist:
                print('输入有误,请重新输入：')
            else:
                getData(new_searchtype, headers, int(start), int(end))
        else:  # 如果是中文就用拼音模块转成拼音再赋值给new_searchtype
            new_searchtype = lazy_pinyin(type)[0] + lazy_pinyin(type)[1]
            if new_searchtype not in typelist:
                print('输入有误,请重新输入：')
            else:
                getData(new_searchtype, headers, int(start), int(end))


def getData(new_searchtype, headers, start, end):
    for i in range(start, end + 1):
        if i == 1:
            url = 'http://pic.netbian.com/4k' + new_searchtype + '/'
        else:
            url = 'http://pic.netbian.com/4k' + new_searchtype + '/' + 'index_' + str(i) + '.html'
        response = requests.get(url=url, headers=headers)
        response.encoding = 'gbk'
        page_text = response.text

        # 解析src属性值，解析alt的属性值
        tree = etree.HTML(page_text)
        # with open()
        li_list = tree.xpath('//*[@id="main"]/div[3]/ul/li')

        # 创建一个文件夹
        if not os.path.exists('./picLibs'):
            os.mkdir('./picLibs')

        for li in li_list:
            name = li.xpath('./a/img/@alt')[0] + '.jpg'
            src = 'http://pic.netbian.com' + li.xpath('./a/img/@src')[0]
            # print(name,src)

            # 请求图片进行储存
            img_data = requests.get(url=src, headers=headers).content
            img_path = 'picLibs/' + name
            with open(img_path, 'wb') as fp:
                fp.write(img_data)
                print(name, '下载完成')


if __name__ == '__main__':
    main()
    messagebox.showinfo("提示", "爬取图片完成,点开文件夹picLibs查看")
